package com.tian.config;

import com.tian.enums.RabbitMQConstantEnum;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

/**
 * {@code @description:} rabbitMQ
 *
 * @author tianwc 公众号：Java后端技术全栈
 * 在线刷题 1200+java面试题和1000+篇技术文章：<a href="https://woaijava.cc/">博客地址</a>
 * {@code @date:} 2024-03-24 9:17
 * {@code @version:} 1.0
 */
@Configuration
public class RabbitConfig {
    @Bean
    public Queue queueMessageUserPoint() {
        return new Queue(RabbitMQConstantEnum.USER_POINT.getQueue(),true);
    }

    @Bean
    TopicExchange exchangeUserPoint() {
        return new TopicExchange(RabbitMQConstantEnum.USER_POINT.getExchange(), true, false);
    }

    @Bean
    Binding bindingExchangeMessageUserPoint(Queue queueMessageUserPoint, TopicExchange exchangeUserPoint) {
        return BindingBuilder.bind(queueMessageUserPoint).to(exchangeUserPoint).with(RabbitMQConstantEnum.USER_POINT.getRoutingKey());
    }

    @Bean
    @Scope("prototype")
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate();
        rabbitTemplate.setConnectionFactory(connectionFactory);
        //设置消息投递失败的策略，有两种策略：自动删除或返回到客户端。
        //我们既然要做可靠性，当然是设置为返回到客户端(true是返回客户端，false是自动删除)
        rabbitTemplate.setMandatory(true);
        return rabbitTemplate;
    }

    @Bean
    public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(ConnectionFactory connectionFactory) {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setAcknowledgeMode(AcknowledgeMode.MANUAL);
        factory.setConnectionFactory(connectionFactory);
        factory.setMessageConverter(new Jackson2JsonMessageConverter());
        return factory;
    }
}
